﻿using AutoMapper;
using Entity.AI.DTO;
using Entity.AI.Entity;
using FrameWork.DataContext;
using FrameWork.Request;
using System.Text;
using System.Text.Json;

namespace Service.AI
{
    public class AIService
    {
        /**
         * 数据库
         */
        private readonly DataContext _context;

        /**
         * 自动映射
         */
        private readonly IMapper _mapper;

        /**
         * http
         */
        private readonly HttpClient _httpClient = new HttpClient();

        /**
         * 构造注入
         */
        public AIService(DataContext context, IMapper mapper)
        {
            _context = context;
            _mapper = mapper;
        }

        /**
         * 获取大模型健康度
         */
        public async Task<RequestResponseModel<AIHealth>> GetModelHealth()
        {
            var response = await _httpClient.GetStringAsync("http://111.229.5.45:8000/api/health");
            var health = JsonSerializer.Deserialize<AIHealth>(response);
            return RequestResponse.CreateResponse(200, "获取成功", health);
        }

        /**
         * 发送消息给大模型
         */
        public async Task<RequestResponseModel<AIChat>> PostModelChat(AIRequestChat aIRequestChat)
        {
            var AIOrder = new AIOrder();
            AIOrder.Id = Guid.NewGuid().ToString();
            AIOrder.UserId = aIRequestChat.userId;
            AIOrder.RequestMessage = aIRequestChat.message;
            AIOrder.RequestTokenLength = aIRequestChat.max_new_tokens;
            AIOrder.RequestTemperature = aIRequestChat.temperature;
            AIOrder.requestTime = DateTime.Now;

            await _context.SaveChangesAsync();

            var jsonContent = new StringContent(
                JsonSerializer.Serialize(aIRequestChat),
                Encoding.UTF8,
                "application/json"
            );
            var response = await _httpClient.PostAsync("http://111.229.5.45:8000/api/chat", jsonContent);
            response.EnsureSuccessStatusCode();
            var responseContent = await response.Content.ReadAsStringAsync();
            var health = JsonSerializer.Deserialize<AIChat>(responseContent);

            AIOrder.ResponseMessage = health.response;
            AIOrder.responseTime = DateTime.Now;
            AIOrder.ResponseTokenLength = health.tokens_used;

            _context.AIOrder.Add(AIOrder);
            await _context.SaveChangesAsync();

            return RequestResponse.CreateResponse(200, "获取成功", health);
        }
    }
}
